package com.wzcl.app.service.impl;

import com.wzcl.app.dao.model.AppResource;
import com.wzcl.app.dao.repository.AppResourceRepository;
import com.wzcl.app.model.dto.ResourceDto;
import com.wzcl.app.service.ResourceService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Log4j2
@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private AppResourceRepository resourceRepository;

    @Override
    public AppResource getResourceById(Integer id) {
        Optional<AppResource> optional = resourceRepository.findById(id);
        return optional.orElse(null);
    }

    @Override
    public List<AppResource> getResourceList(ResourceDto resourceDto) {
        return resourceRepository.findAll(getSpecification(resourceDto), resourceDto.getSort());
    }

    private Specification<AppResource> getSpecification(ResourceDto resourceDto) {
        return new Specification<AppResource>() {
            @Override
            public Predicate toPredicate(Root<AppResource> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
    }
}
